package com.bawei.publish

import android.app.ProgressDialog
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Build
import android.util.Base64
import android.util.Log
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.base.RoutePath
import com.bawei.common.mvi.BaseMviActivity
import com.bawei.publish.databinding.ActivityTakeVideoBinding
import com.qiniu.pili.droid.shortvideo.PLAudioEncodeSetting
import com.qiniu.pili.droid.shortvideo.PLCameraSetting
import com.qiniu.pili.droid.shortvideo.PLFaceBeautySetting
import com.qiniu.pili.droid.shortvideo.PLGifWatermarkSetting
import com.qiniu.pili.droid.shortvideo.PLMicrophoneSetting
import com.qiniu.pili.droid.shortvideo.PLRecordSetting
import com.qiniu.pili.droid.shortvideo.PLRecordStateListener
import com.qiniu.pili.droid.shortvideo.PLShortVideoRecorder
import com.qiniu.pili.droid.shortvideo.PLVideoEncodeSetting
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener
import com.qiniu.pili.droid.shortvideo.PLWatermarkSetting
import kotlinx.coroutines.launch
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

@Route(path = RoutePath.PATH_RECORDER_PAGE)
class TakeVideoActivity : BaseMviActivity<ActivityTakeVideoBinding>() {

    private lateinit var mPlShortVideoRecord: PLShortVideoRecorder
    private var recordeState: RecodeState = RecodeState.PENDING
    private lateinit var processDialog: ProgressDialog


    override fun getLayoutId(): Int = R.layout.activity_take_video

    override fun initViews() {
        initQiNiuVideoRecorder()
        setQiNiuRecorderParams()

        //开始录制
        mDataBinding.ivPublishTakeBegin.setOnClickListener {
            recordeState = RecodeState.PENDING
            updateUI(recordeState)
            mPlShortVideoRecord.beginSection()
            recordeState = RecodeState.RECODING
        }

        //暂停录制
        mDataBinding.ivPublishTakePause.setOnClickListener {
            recordeState = RecodeState.PAUSE
            updateUI(recordeState)
            mPlShortVideoRecord.endSection()
        }


        //恢复录制
        mDataBinding.ivResume.setOnClickListener {
            recordeState = RecodeState.RESUMED
            updateUI(recordeState)
            mPlShortVideoRecord.beginSection()
        }


        //停止录制
        mDataBinding.ivPublishTakeStop.setOnClickListener {
            recordeState = RecodeState.STOP
            mPlShortVideoRecord.endSection()

            //合成进度提示
            processDialog = ProgressDialog(this@TakeVideoActivity).apply {
                setTitle("合成中")
                setMessage("视频合成中请稍等...")
                setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
                isIndeterminate = true
            }
            processDialog.show()


            mPlShortVideoRecord.concatSections(object : PLVideoSaveListener{
                override fun onSaveVideoSuccess(p0: String?) {
                    //保存到数据中
                    lifecycleScope.launch {

                    }

                    //使用协程上下文切换线程
//                    lifecycleScope.launch(Dispatchers.Main) {
//                        updateUI(recordeState)
//                    }

                    //切换到主线程中更新UI
                    runOnUiThread{
                        processDialog.dismiss()
                        updateUI(recordeState)
                    }

                }

                override fun onSaveVideoFailed(p0: Int) {
                    runOnUiThread{
                        processDialog.dismiss()
                        updateUI(recordeState)
                        showToastMsg("保存失败！errorCode:${p0}")
                    }
                }

                override fun onSaveVideoCanceled() {
                    runOnUiThread{
                        processDialog.dismiss()
                        updateUI(recordeState)
                        showToastMsg("取消保存！")
                    }
                }

                override fun onProgressUpdate(p0: Float) {
                    processDialog.progress = (p0 * 100).toInt()
                }
            })

        }

        //关闭
        mDataBinding.ivClose.setOnClickListener {
            this@TakeVideoActivity.finish()
        }

        //保存到草稿箱
        mDataBinding.tvSaveDraft.setOnClickListener {
            mPlShortVideoRecord.saveToDraftBox("draft_${System.currentTimeMillis()}")
            showToastMsg("保存草稿箱成功！")
        }
    }


    private fun updateUI(state: RecodeState){
        when(state){
            RecodeState.PENDING -> {
                mDataBinding.ivPublishTakeBegin.visibility = View.GONE
                mDataBinding.llPauseStop.visibility = View.VISIBLE
                mDataBinding.ivResume.visibility = View.GONE
            }

            RecodeState.PAUSE -> {
                mDataBinding.ivPublishTakeBegin.visibility = View.GONE
                mDataBinding.llPauseStop.visibility = View.GONE
                mDataBinding.ivResume.visibility = View.VISIBLE
            }

            RecodeState.RESUMED -> {
                mDataBinding.ivPublishTakeBegin.visibility = View.GONE
                mDataBinding.llPauseStop.visibility = View.VISIBLE
                mDataBinding.ivResume.visibility = View.GONE

            }

            RecodeState.STOP -> {
                mDataBinding.ivPublishTakeBegin.visibility = View.VISIBLE
                mDataBinding.llPauseStop.visibility = View.GONE
                mDataBinding.ivResume.visibility = View.GONE
            }

            RecodeState.RECODING -> { }

        }

    }


    private fun initQiNiuVideoRecorder(){
        mPlShortVideoRecord = PLShortVideoRecorder()
        mPlShortVideoRecord.setRecordStateListener(object : PLRecordStateListener {
            override fun onReady() {
                Log.i("TakeVideoActivity", "========= onReady: ======")
            }

            override fun onError(p0: Int) {
                Log.i("TakeVideoActivity", "========= onError: ======")
            }

            override fun onDurationTooShort() {
                Log.i("TakeVideoActivity", "========= onDurationTooShort: ======")
            }

            override fun onRecordStarted() {
                Log.i("TakeVideoActivity", "========= onRecordStarted: ======")
            }

            override fun onSectionRecording(p0: Long, p1: Long, p2: Int) {
                Log.i("TakeVideoActivity", "========= onSectionRecording: ======")
            }

            override fun onRecordStopped() {
                Log.i("TakeVideoActivity", "========= onRecordStopped: ======")
            }

            override fun onSectionIncreased(p0: Long, p1: Long, p2: Int) {
                Log.i("TakeVideoActivity", "========= onSectionIncreased: ======")
            }

            override fun onSectionDecreased(p0: Long, p1: Long, p2: Int) {
                Log.i("TakeVideoActivity", "========= onSectionDecreased: ======")
            }

            override fun onRecordCompleted() {
                Log.i("TakeVideoActivity", "========= onRecordCompleted: ======")
            }

        })
    }

    /**
     * 配置相机相关参数
     */
    private fun setQiNiuRecorderParams(){
        //相机设置
        var camaraSetting = PLCameraSetting().apply {
            cameraId = PLCameraSetting.CAMERA_FACING_ID.CAMERA_FACING_FRONT // 相机ID
            cameraPreviewSizeRatio = PLCameraSetting.CAMERA_PREVIEW_SIZE_RATIO.RATIO_4_3 //预览比例大小
            cameraPreviewSizeLevel = PLCameraSetting.CAMERA_PREVIEW_SIZE_LEVEL.PREVIEW_SIZE_LEVEL_480P //预览分辨率大小
        }

        //麦克风设置
        var microphoneSetting = PLMicrophoneSetting()

        //视频编码设置
        var videoEncodeSetting = PLVideoEncodeSetting(this@TakeVideoActivity).apply {
            encodingSizeLevel = PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_720P_2 //480*960
            encodingBitrate = 1000 * 1024 //1000kbps
            isHWCodecEnabled = true //true: 硬编码，false：软编码
            setEncodingFps(30) //帧率
        }

        //麦克风编码设置
        var audioEncodeSetting = PLAudioEncodeSetting().apply {
            isHWCodecEnabled = true
        }

        //美颜配置
        var faceBeautySetting = PLFaceBeautySetting(1.0f, 0.5f, 0.5f)

        //录制设置
        var recordSetting = PLRecordSetting().apply {
            maxRecordDuration = 10 * 1000L
            setVideoCacheDir("/sdcard")
            var currentTime: String = "20241007114511"
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
                currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
            }
            videoFilepath = "/sdcard/bw_dev_$currentTime.mp4"
        }

        //水印设置
        var watermarkSetting = PLWatermarkSetting().apply {
            resourceId = com.bawei.base.R.drawable.ic_logo//makeStringToBitmap("I视频项目")
            setPosition(0.75f, 0.75f)
            alpha = 128
        }
//        mPlShortVideoRecord.setWatermark(watermarkSetting)

        //准备录制视频
        mPlShortVideoRecord.prepare(mDataBinding.glSurfaceView, camaraSetting, microphoneSetting, videoEncodeSetting, audioEncodeSetting, faceBeautySetting, recordSetting)

    }

    private fun makeStringToBitmap(str: String): Bitmap{
        //准备画笔
        var paint = Paint().apply {
            color = Color.BLACK
            textSize = 18F
            isAntiAlias = true
        }

        //测量文本宽高
        var textWidth = paint.measureText(str)
        var textHeight = paint.descent() - paint.ascent()

        var bitmap = Bitmap.createBitmap(textWidth.toInt(), textHeight.toInt(), Bitmap.Config.ARGB_8888)
        var canvas = Canvas(bitmap)
        canvas.drawColor(Color.WHITE) //颜色
        canvas.drawText(str, 0F, -paint.ascent(), paint) //文本

        return bitmap
    }


    override fun onResume() {
        super.onResume()
        mPlShortVideoRecord?.resume()
    }

    override fun onPause() {
        super.onPause()
        mPlShortVideoRecord?.pause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mPlShortVideoRecord?.destroy()
    }

    /**
     * 录制UI状态
     */
    enum class RecodeState{
        PENDING, RECODING, PAUSE, STOP, RESUMED
    }




}